document.addEventListener('DOMContentLoaded', function() {
    loadTags();
    setupTagEventListeners();
});

function loadTags() {
    const category = document.querySelector('#tagCategories .active').dataset.category;
    const search = document.getElementById('tagSearch').value;
    const sort = document.getElementById('tagSort').value;

    fetch(`/api/tags?category=${category}&search=${search}&sort=${sort}`)
        .then(response => response.json())
        .then(tags => {
            renderTags(tags);
        });
}

function renderTags(tags) {
    const tagList = document.getElementById('tagList');
    tagList.innerHTML = '';

    tags.forEach(tag => {
        const tagElement = document.createElement('div');
        tagElement.className = 'tag-item';
        tagElement.innerHTML = `
            <div class="card mb-2">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">
                            ${tag.name}
                            <span class="badge bg-primary" style="background-color: #1976D2 !important">${tag.category}</span>
                        </h5>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-primary edit-tag" style="color: #1976D2; border-color: #1976D2" data-id="${tag.id}" aria-label="编辑标签">
                                <i class="mdi mdi-pencil" aria-hidden="true"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger delete-tag" style="color: #C62828; border-color: #C62828" data-id="${tag.id}" aria-label="删除标签">
                                <i class="mdi mdi-delete" aria-hidden="true"></i>
                            </button>
                        </div>
                    </div>
                    <p class="card-text text-muted small mb-2">${tag.description || '暂无描述'}</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">使用次数: ${tag.usage_count}</small>
                        <button class="btn btn-sm btn-link view-users" style="color: #1976D2" data-id="${tag.id}" aria-label="查看使用此标签的用户">
                            查看用户
                        </button>
                    </div>
                </div>
            </div>
        `;
        tagList.appendChild(tagElement);
    });
}

function setupTagEventListeners() {
    // Category selection
    document.getElementById('tagCategories').addEventListener('click', (e) => {
        e.preventDefault();
        const item = e.target.closest('.list-group-item');
        if (!item) return;

        document.querySelectorAll('#tagCategories .list-group-item').forEach(el => {
            el.classList.remove('active');
        });
        item.classList.add('active');
        loadTags();
    });

    // Search input
    let searchTimeout;
    document.getElementById('tagSearch').addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => loadTags(), 300);
    });

    // Sort selection
    document.getElementById('tagSort').addEventListener('change', () => loadTags());

    // Add tag form submission
    document.getElementById('saveTagBtn').addEventListener('click', () => {
        const form = document.getElementById('addTagForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        fetch('/api/tags', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            $('#addTagModal').modal('hide');
            loadTags();
            form.reset();
        });
    });

    // Tag actions (edit, delete, view users)
    document.getElementById('tagList').addEventListener('click', (e) => {
        const btn = e.target.closest('button');
        if (!btn) return;

        const tagId = btn.dataset.id;

        if (btn.classList.contains('edit-tag')) {
            // Handle edit tag
            fetch(`/api/tags/${tagId}`)
                .then(response => response.json())
                .then(tag => {
                    // Populate and show edit modal
                    // TODO: Implement edit tag modal
                });
        } else if (btn.classList.contains('delete-tag')) {
            if (confirm('确定要删除这个标签吗？')) {
                fetch(`/api/tags/${tagId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        loadTags();
                    }
                });
            }
        } else if (btn.classList.contains('view-users')) {
            // 获取并显示用户列表
            fetch(`/api/tags/${tagId}/users`)
                .then(response => response.json())
                .then(users => {
                    const usersList = document.getElementById('tagUsersList');
                    usersList.innerHTML = users.map(user => `
                        <tr>
                            <td>${user.username}</td>
                            <td>${user.email}</td>
                            <td>${user.membership_level}</td>
                            <td>
                                <a href="/user-profile/${user.id}" class="btn btn-sm btn-primary" style="background-color: #1976D2; border-color: #1976D2">
                                    查看档案
                                </a>
                            </td>
                        </tr>
                    `).join('');
                    
                    new bootstrap.Modal(document.getElementById('viewUsersModal')).show();
                });
        }
    });

    // Rule type change handler
    document.querySelector('select[name="rule_type"]').addEventListener('change', (e) => {
        const ruleType = e.target.value;
        const ruleConditions = document.getElementById('ruleConditions');
        
        if (ruleType === 'simple') {
            ruleConditions.innerHTML = `
                <div class="input-group mb-2">
                    <select class="form-select" name="field">
                        <option value="consumption_score">消费能力得分</option>
                        <option value="order_count">订单数量</option>
                        <option value="total_amount">消费总额</option>
                    </select>
                    <select class="form-select" name="operator">
                        <option value="gt">大于</option>
                        <option value="lt">小于</option>
                        <option value="eq">等于</option>
                    </select>
                    <input type="number" class="form-control" name="value" placeholder="值">
                </div>
            `;
        } else {
            ruleConditions.innerHTML = `
                <div class="alert alert-info">
                    复合规则支持多个条件组合，请使用高级编辑器设置规则。
                </div>
                <button type="button" class="btn btn-outline-primary" id="openRuleEditor">
                    打开规则编辑器
                </button>
            `;
        }
    });
}
